//
//  MessageCell.m
//  BaiTengIM
//
//  Created by awh on 2019/6/29.
//  Copyright © 2019 awh. All rights reserved.
//

#import "MessageCell.h"

#import "MessageStatusView.h"

#import "MessageTextBubbleView.h"
#import "MessageVoiceBubbleView.h"
#import "MessageImageBubbleView.h"

@interface MessageCell ()<MessageBubbleViewDelegate>

@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) CAShapeLayer *avatarBorder;


@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *roleLabel; // 角色
@property (nonatomic, strong) MessageStatusView *statusView;


@end

@implementation MessageCell

+ (NSString *)cellIdentifierWithDirection:(MessageDirection)messageDirection
                                     type:(MessageType)messageType {
    NSString *identifier = messageDirection == MessageDirectionSend ? @"messageCellDirectionSend" : @"messageCellDirectionReceive";
    if (messageType == MessageTypeText) {
        identifier = [NSString stringWithFormat:@"%@Text", identifier];
    } else if (messageType == MessageTypeImage) {
        identifier = [NSString stringWithFormat:@"%@Image", identifier];
    } else if (messageType == MessageTypeVoice) {
        identifier = [NSString stringWithFormat:@"%@Voice", identifier];
    }
    return identifier;
}

- (instancetype)initWithDirection:(MessageDirection)messageDirection type:(MessageType)messageType {
    NSString *identifier = [MessageCell cellIdentifierWithDirection:messageDirection type:messageType];
    if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]) {
        _messageDirection = messageDirection;
        [self setupSubviewsWithType:messageType];
    }
    return self;
}

- (void)setupSubviewsWithType:(MessageType)messageType{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = self.contentView.backgroundColor = [UIColor clearColor];
    // 头像
    _avatarView = [[UIImageView alloc] init];
    [_avatarView addTapCallBack:self sel:@selector(clickAvatarViewAction)];
    _avatarView.userInteractionEnabled = YES;
    [_avatarView configLayerWithBorderWidth:0 andWithCornerRadius:20 andWithBorderColor:[UIColor clearColor]];
    [self.contentView addSubview:_avatarView];
    
    // 头像边框
    _avatarBorder = [CAShapeLayer layer];
    _avatarBorder.strokeColor = KRGBACOLOR(242,72,160, 1.0).CGColor;
    _avatarBorder.fillColor = [UIColor clearColor].CGColor;
    _avatarBorder.path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 40, 40)].CGPath;
    _avatarBorder.frame = self.avatarView.bounds;
    _avatarBorder.lineWidth = 1.f;
    _avatarBorder.lineDashPattern = @[@4, @2];
//    [_avatarView.layer addSublayer:_avatarBorder];
    
    // 名称
    _nameLabel = [[UILabel alloc] init];
    _nameLabel.font = [UIFont systemFontOfSize:13];
    _nameLabel.textColor = [UIColor grayColor];
    [self.contentView addSubview:_nameLabel];
    // 角色
    _roleLabel = [UILabel new];
    _roleLabel.font = [UIFont systemFontOfSize:13];
    _roleLabel.textColor = [UIColor whiteColor];
    _roleLabel.backgroundColor = [UIColor orangeColor];
    _roleLabel.textAlignment = 1;
    [self.contentView addSubview:_roleLabel];
    if (self.messageDirection == MessageDirectionSend) {
        _avatarView.image = [UIImage imageNamed:@"user_avatar_me"];
        [_avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(15);
            make.right.equalTo(self.contentView).offset(-10);
            make.width.height.equalTo(@40);
        }];
        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarView);
            make.right.equalTo(self.avatarView.mas_left).offset(-8);
            make.width.lessThanOrEqualTo(@300);
        }];
        [_roleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarView);
            make.right.equalTo(self.nameLabel.mas_left).offset(-8);
            make.width.equalTo(@40);
        }];
    } else {
        _avatarView.image = [UIImage imageNamed:@"user_avatar_blue"];
        [_avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(15);
            make.left.equalTo(self.contentView).offset(10);
            make.width.height.equalTo(@40);
        }];
        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarView);
            make.left.equalTo(self.avatarView.mas_right).offset(8);
            make.width.lessThanOrEqualTo(@300);
        }];
        [_roleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.avatarView);
            make.left.equalTo(self.nameLabel.mas_right).offset(8);
            make.width.equalTo(@40);
        }];
    }
    
    _bubbleView = [self getBubbleViewWithType:messageType];
    _bubbleView.userInteractionEnabled = YES;
    _bubbleView.clipsToBounds = YES;
    [self.contentView addSubview:_bubbleView];
    if (self.messageDirection == MessageDirectionSend) {
        [_bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_bottom).offset(16);
            make.bottom.equalTo(self.contentView).offset(-15);
            make.left.greaterThanOrEqualTo(self.contentView).offset(70);
            make.right.equalTo(self.avatarView.mas_left).offset(-10);
        }];
    } else {
        [_bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_bottom).offset(16);
            make.bottom.equalTo(self.contentView).offset(-15);
            make.left.equalTo(self.avatarView.mas_right).offset(10);
            make.right.lessThanOrEqualTo(self.contentView).offset(-70);
        }];
    }
    
    _statusView = [[MessageStatusView alloc] init];
    [self.contentView addSubview:_statusView];
    if (self.messageDirection == MessageDirectionSend) {
        [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView.mas_centerY);
            make.right.equalTo(self.bubbleView.mas_left).offset(-8);
            make.height.equalTo(@20);
        }];
        __weak typeof(self) weakself = self;
        [_statusView setResendCompletion:^{
            if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(messageCellDidResend:)]) {
                [weakself.delegate messageCellDidResend:weakself.model];
            }
        }];
    } else {
        _statusView.backgroundColor = [UIColor redColor];
        _statusView.clipsToBounds = YES;
        _statusView.layer.cornerRadius = 4;
        [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.bubbleView).offset(5);
            make.left.equalTo(self.bubbleView.mas_right).offset(5);
            make.width.height.equalTo(@8);
        }];
    }
}

- (MessageBubbleView *)getBubbleViewWithType:(MessageType)messageType {
    MessageBubbleView *bubbleView = nil;
    switch (messageType) {
        case MessageTypeText:
            bubbleView = [[MessageTextBubbleView alloc] initWithDirection:self.messageDirection type:messageType];
            bubbleView.delegate = self;
            break;
        case MessageTypeVoice:
            bubbleView = [[MessageVoiceBubbleView alloc] initWithDirection:self.messageDirection type:messageType];
            break;
        case MessageTypeImage:
            bubbleView = [[MessageImageBubbleView alloc] initWithDirection:self.messageDirection type:messageType];
            break;
        default:
            break;
    }
    if (bubbleView) {
        if (messageType != MessageTypeText) {
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bubbleViewTapAction:)];
            [bubbleView addGestureRecognizer:tap];
        }
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(bubbleViewLongPressAction:)];
        [bubbleView addGestureRecognizer:longPress];
    }
    
    return bubbleView;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.roleLabel.layer setMasksToBounds:YES];
    self.roleLabel.layer.cornerRadius = self.roleLabel.height / 2;
//    [self setCornerOnTop:self.roleLabel.height / 2 withView:self.roleLabel];

}
- (void)setCornerOnTop:(CGFloat )cornerRadius withView:(UIView*)view{
    UIBezierPath *maskPath;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                     byRoundingCorners:(UIRectCornerAllCorners)
                                           cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)setModel:(BTMessageModel *)model {
  
    _model = model;
    NSString *avatar = @"";
    if (model.messageDirection == MessageDirectionSend) {
        if ([[LoginManager shareLoginManager].userModel.head containsString:@"http"]) {
            avatar= [LoginManager shareLoginManager].userModel.head;
        }else
        {
            avatar= [NSString stringWithFormat:@"%@%@",userHeaderImage, [LoginManager shareLoginManager].userModel.head];
        }
    }else
    {
        avatar=[NSString stringWithFormat:@"%@%@",userHeaderImage, model.head];
    }
    [self.avatarView sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:kHeadPlaceholderImage];
    self.bubbleView.model = model;
    if (model.messageDirection == MessageDirectionSend) {
        self.statusView.hidden = NO;
        [self.statusView setSenderStatus:model.messageStatus];
    } else {
        self.statusView.hidden = YES;
    }
    
    
}

#pragma mark - Action

- (void)bubbleViewTapAction:(UITapGestureRecognizer *)aTap {
    if (aTap.state == UIGestureRecognizerStateEnded) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(messageCellDidSelected:)]) {
            [self.delegate messageCellDidSelected:self];
        }
    }
}

- (void)bubbleViewLongPressAction:(UILongPressGestureRecognizer *)aLongPress {
    if (aLongPress.state == UIGestureRecognizerStateBegan) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(messageCellDidLongPress:)]) {
            [self.delegate messageCellDidLongPress:self];
        }
    }
}
-(void)clickAvatarViewAction
{
    if ([self.delegate respondsToSelector:@selector(didSelecedUserHead:)]) {
        [self.delegate didSelecedUserHead:self];
    }
}

#pragma mark - MessageBubbleViewDelegate

- (void)messageBubbleView:(MessageBubbleView *)bubbleView didClickURL:(NSString *)urlStr {
    if (self.delegate && [self.delegate respondsToSelector:@selector(messageCellDidClickUrl:)]) {
        [self.delegate messageCellDidClickUrl:urlStr];
    }
}

@end
